    package com.edu.bhu.admin.controller.admin;

import java.util.*;
import java.util.stream.Collectors;

import com.edu.bhu.admin.domain.LibBook;
import com.edu.bhu.admin.domain.QueryLoan;
import com.edu.bhu.admin.service.ILibBookService;
import com.edu.bhu.common.core.domain.entity.SysUser;
import com.edu.bhu.common.utils.DateUtils;
import com.edu.bhu.common.utils.StringUtils;
import io.swagger.models.auth.In;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.edu.bhu.common.annotation.Log;
import com.edu.bhu.common.enums.BusinessType;
import com.edu.bhu.admin.domain.LibLoan;
import com.edu.bhu.admin.service.ILibLoanService;
import com.edu.bhu.common.core.controller.BaseController;
import com.edu.bhu.common.core.domain.AjaxResult;
import com.edu.bhu.common.utils.poi.ExcelUtil;
import com.edu.bhu.common.core.page.TableDataInfo;

/**
 * 借阅信息Controller
 * 
 * @author wangweibo
 * @date 2022-02-14
 */
@Controller
@RequestMapping("/admin/loan")
public class LibLoanController extends BaseController
{
    private String prefix = "admin/loan";

    @Autowired
    private ILibLoanService libLoanService;

    @Autowired
    private ILibBookService  libBookService;

    @RequiresPermissions("admin:loan:view")
    @GetMapping()
    public String loan()
    {
        return prefix + "/loan";
    }

    /**
     * 我的借阅信息页面
     */
    @RequiresPermissions("admin:loan:redview")
    @GetMapping("/myLoan")
    public String myLoan()
    {
        return prefix + "/myLoan";
    }

    /**
     * 选择借阅图书页面
     */
    @RequiresPermissions("admin:loan:redview")
    @GetMapping("/selectBook")
    public String selectBook()
    {
        return prefix + "/selectBook";
    }

    /**
     * 图书借阅选项页面（选择归还时间）
     */
    @RequiresPermissions("admin:loan:redview")
    @GetMapping("/goAddLoan/{ids}")
    public String goAddLoan(@PathVariable("ids") String ids, ModelMap mmap)
    {
        mmap.put("ids",ids);
        return prefix + "/addLoan";
    }

    /**
     * 借阅信息回收页面
     */
    @RequiresPermissions("admin:loan:view")
    @GetMapping("/loanRecycle")
    public String loanRecycle()
    {
        return prefix + "/loanRecycle";
    }

    /**
     * 查询借阅信息列表（根据当前用户id，不分页）
     */
    @RequiresPermissions("admin:loan:list")
    @PostMapping("/listNotPageByUserId")
    @ResponseBody
    public TableDataInfo listNotPageByUserId(LibLoan libLoan)
    {
        SysUser user = new SysUser();
        user.setUserId(getSysUser().getUserId());
        libLoan.setSysUser(user);
        List<LibLoan> list = libLoanService.selectLibLoanWithInfoList(libLoan,libLoan.getLibBook(),libLoan.getSysUser());
        return getDataTable(list);
    }

    /**
     * 查询借阅信息列表
     */
    @RequiresPermissions("admin:loan:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(LibLoan libLoan)
    {
        startPage();
        List<LibLoan> list = libLoanService.selectLibLoanList(libLoan);
        return getDataTable(list);
    }

    /**
     * 查询借阅信息列表(关联用户和书本信息)
     */
    @RequiresPermissions("admin:loan:list")
    @PostMapping("/listWithInfo")
    @ResponseBody
    public TableDataInfo listWithInfo(LibLoan libLoan, QueryLoan quaryLoan)
    {
        startPage();

        //图书名称、编号查询
        LibBook libBook = new LibBook();
        if (StringUtils.isNotEmpty(quaryLoan.getBookName()))
        {
            libBook.setName(quaryLoan.getBookName());
        }
        if (StringUtils.isNotEmpty(quaryLoan.getBookNo()))
        {
            libBook.setBookNo(quaryLoan.getBookNo());
        }
        libLoan.setLibBook(libBook);

        //用户名称、ID查询
        SysUser sysUser = new SysUser();
        if (StringUtils.isNotEmpty(quaryLoan.getUserName()))
        {
           sysUser.setUserName(quaryLoan.getUserName());
        }
        if (StringUtils.isNotNull(quaryLoan.getUserId()))
        {
            sysUser.setUserId(quaryLoan.getUserId());
        }
        libLoan.setSysUser(sysUser);

        List<LibLoan> list = libLoanService.selectLibLoanWithInfoList(libLoan,libLoan.getLibBook(),libLoan.getSysUser());

        //筛选对应状态的条目
        if (StringUtils.isNotEmpty(quaryLoan.getLoanStatus()))
        {
            list = list.stream().filter(item ->
                    item.getLoanStatus() == Long.valueOf(quaryLoan.getLoanStatus())
            ).collect(Collectors.toList());
        }

        return getDataTable(list);
    }

    /**
     * 查询借阅信息列表(关联用户和书本信息)(删除的)
     */
    @RequiresPermissions("admin:loan:list")
    @PostMapping("/listWithInfoDel")
    @ResponseBody
    public TableDataInfo listWithInfoDel(LibLoan libLoan, QueryLoan quaryLoan)
    {
        startPage();

        //图书名称、编号查询
        LibBook libBook = new LibBook();
        if (StringUtils.isNotEmpty(quaryLoan.getBookName()))
        {
            libBook.setName(quaryLoan.getBookName());
        }
        if (StringUtils.isNotEmpty(quaryLoan.getBookNo()))
        {
            libBook.setBookNo(quaryLoan.getBookNo());
        }
        libLoan.setLibBook(libBook);

        //用户名称、ID查询
        SysUser sysUser = new SysUser();
        if (StringUtils.isNotEmpty(quaryLoan.getUserName()))
        {
            sysUser.setUserName(quaryLoan.getUserName());
        }
        if (StringUtils.isNotNull(quaryLoan.getUserId()))
        {
            sysUser.setUserId(quaryLoan.getUserId());
        }
        libLoan.setSysUser(sysUser);

        List<LibLoan> list = libLoanService.selectLibLoanWithInfoListDel(libLoan,libLoan.getLibBook(),libLoan.getSysUser());

        //筛选对应状态的条目
        if (StringUtils.isNotEmpty(quaryLoan.getLoanStatus()))
        {
            list = list.stream().filter(item ->
                    item.getLoanStatus() == Long.valueOf(quaryLoan.getLoanStatus())
            ).collect(Collectors.toList());
        }

        return getDataTable(list);
    }

    /**
     * 借阅图书-图书列表
     */
    @RequiresPermissions("admin:loan:list")
    @PostMapping("/selectList")
    @ResponseBody
    public TableDataInfo selectList(LibBook libBook)
    {
        startPage();
        //只显示没有停用和没有被借出的图书
        libBook.setStatus(1L);
        libBook.setLoanStatus(1L);
        List<LibBook> list = libBookService.selectLibBookWithTypeList(libBook);
        return getDataTable(list);
    }

    /**
     * 批量新增借阅信息 wangweibo
     */
    @RequiresPermissions("admin:loan:add")
    @Log(title = "借阅信息", businessType = BusinessType.DELETE)
    @PostMapping( "/batchAdd")
    @ResponseBody
    public AjaxResult batchAdd(String ids, Date date)
    {
        LibLoan libLoan = new LibLoan();
        libLoan.setUserId(getSysUser().getUserId());
        libLoan.setPreReturnTime(date);
        return toAjax(libLoanService.insertLibLoanBatch(ids,libLoan));
    }

    /**
     * 导出借阅信息列表
     */
    @RequiresPermissions("admin:loan:export")
    @Log(title = "借阅信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(LibLoan libLoan)
    {
        List<LibLoan> list = libLoanService.selectLibLoanList(libLoan);
        ExcelUtil<LibLoan> util = new ExcelUtil<LibLoan>(LibLoan.class);
        return util.exportExcel(list, "借阅信息数据");
    }

    /**
     * 新增借阅信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存借阅信息
     */
    @RequiresPermissions("admin:loan:add")
    @Log(title = "借阅信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(LibLoan libLoan)
    {
        return toAjax(libLoanService.insertLibLoan(libLoan));
    }

    /**
     * 图书归还（读者）
     */
    @RequiresPermissions("admin:loan:edit")
    @Log(title = "借阅信息", businessType = BusinessType.UPDATE)
    @PostMapping("/addReturn")
    @ResponseBody
    public AjaxResult addReturn(Long loanId)
    {
        LibLoan libLoan = libLoanService.selectLibLoanByLoanId(loanId);
        //在libbook修改借出状态为未借出
        LibBook libBook = new LibBook();
        libBook.setBookId(libLoan.getBookId());
        libBook.setLoanStatus(1L);
        libBookService.updateLibBook(libBook);

        //在libLoan添加归还日期
        LibLoan libLoan1 = new LibLoan();
        libLoan1.setLoanId(libLoan.getLoanId());
        libLoan1.setPraReturnTime(DateUtils.truncate(DateUtils.getNowDate(), Calendar.DAY_OF_MONTH));

        return toAjax(libLoanService.updateLibLoan(libLoan1));
    }


    /**
     * 修改借阅信息
     */
    @RequiresPermissions("admin:loan:edit")
    @GetMapping("/edit/{loanId}")
    public String edit(@PathVariable("loanId") Long loanId, ModelMap mmap)
    {
        LibLoan libLoan = libLoanService.selectLibLoanByLoanId(loanId);
        mmap.put("libLoan", libLoan);
        return prefix + "/edit";
    }

    /**
     * 修改保存借阅信息
     */
    @RequiresPermissions("admin:loan:edit")
    @Log(title = "借阅信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(LibLoan libLoan)
    {
        return toAjax(libLoanService.updateLibLoan(libLoan));
    }

    /**
     * 删除借阅信息
     */
    @RequiresPermissions("admin:loan:remove")
    @Log(title = "借阅信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(libLoanService.deleteLibLoanByLoanIds(ids));
    }

    /**
     * 删除借阅信息
     */
    @RequiresPermissions("admin:loan:remove")
    @Log(title = "借阅信息", businessType = BusinessType.DELETE)
    @PostMapping( "/removeForever")
    @ResponseBody
    public AjaxResult removeForever(String ids)
    {
        return toAjax(libLoanService.deleteLibLoanByLoanIdsForever(ids));
    }

    /**
     * 批量还原删除数据 wangweibo
     */
    @RequiresPermissions("admin:loan:edit")
    @Log(title = "借阅信息", businessType = BusinessType.UPDATE)
    @PostMapping( "/batchRestore")
    @ResponseBody
    public AjaxResult batchRestore(String ids)
    {
        return toAjax(libLoanService.updateLibLoanBatch(ids));
    }
}
